package jk.spider.util.xml;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.LazyDynaMap;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class XmlHelp {
	protected static final Logger log = Logger.getLogger(XmlHelp.class);
	protected static final String CONF_FILE = "D:/eclipse/workspace/JK_Spider-2.0/config/parser/Food.xml";
	protected static Document doc;
	private static String nodeName;
	protected static Map<String, LazyDynaMap> configMap;
	protected static LazyDynaMap ldm ;
	
	public static void main(String[] args) {
		Map<String, LazyDynaMap> lMap = loadXml(CONF_FILE);
		LazyDynaMap lObj = lMap.get("dianping");
		List<String> p = (List<String>)lObj.get("price");
		String tc = (String)lObj.get("pClass");
		System.out.println(lObj.get("price"));
		System.out.println(p.get(0));
		System.out.println(tc);
//		System.out.println(lMap.get("dianping"));
	}
	
	public synchronized static Map<String, LazyDynaMap> loadXml(String file) {
		if(configMap != null)
			return configMap;	
		configMap = new HashMap<String, LazyDynaMap>();
		SAXReader reader = new SAXReader();
		try {
			doc = reader.read(new File(file));
		} catch (DocumentException e) {
			log.error("loadXml DocumentException ->", e);
		}
		treeWalk();
		return configMap;
	}
	
	public synchronized static LazyDynaMap getLazyDyMap(String site) {
		return configMap.get(site);
	}
	
	public LazyDynaMap getXMLObject() {
		return ldm;
	}
	
	protected static void treeWalk() {
		Element root = doc.getRootElement();
		try {
			treeWalk(root);
		} catch (IllegalAccessException e) {
			log.error("treeWalk IllegalAccessException ->", e);
		} catch (InvocationTargetException e) {
			log.error("treeWalk InvocationTargetException ->", e);
		} catch (NoSuchMethodException e) {
			log.error("treeWalk NoSuchMethodException -> ", e);
		}
	}
	
	public static void treeWalk(Element element) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		int r = 0;
		for (int i = 0, size = element.nodeCount(); i < size; i++) {
			Node node = element.node(i);
			if (node instanceof Element) {
				if(((Element) node).attributeCount() > 0) {
					String site = ((Element) node).attributeValue("name");
					String pClass = ((Element) node).attributeValue("class");
					ldm = new LazyDynaMap();
					ldm.set("site", site);
					ldm.set("pClass", pClass);
					configMap.put(site, ldm);
				} else if(node.getName().equals("reg")) {
					ldm.set(nodeName, r ++ , node.getText());
				} else {
					nodeName = node.getName();
				}
				treeWalk((Element) node);
			} 
		}
	}
	
}
